/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
package example.springboot.service;

import example.springboot.dto.WordDTO;
import example.springboot.entity.ErrorBook;
import example.springboot.entity.Word;
import example.springboot.mapper.ErrorBookMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ErrorBookService {

    @Autowired
    private ErrorBookMapper errorBookMapper;

    /**
     * 添加或更新错题
     */
    public void addOrUpdateError(Integer userId, Integer wordId) {
        // 先检查是否存在
        int count = errorBookMapper.checkExists(userId, wordId);
        if (count > 0) {
            // 更新错误次数
            errorBookMapper.updateErrorCount(userId, wordId);
        } else {
            // 插入新记录
            ErrorBook errorBook = new ErrorBook();
            errorBook.setUserId(userId);
            errorBook.setWordId(wordId);
            errorBook.setErrorCount(1);
            errorBookMapper.insert(errorBook);
        }
    }

    /**
     * 获取用户的错题列表
     */
    public List<WordDTO> getErrorWords(Integer userId) {
        List<Word> words = errorBookMapper.findErrorWordsByUserId(userId);
        
        return words.stream().map(word -> {
            WordDTO dto = new WordDTO();
            BeanUtils.copyProperties(word, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 删除错题
     */
    public boolean removeError(Integer userId, Integer wordId) {
        return errorBookMapper.deleteByUserIdAndWordId(userId, wordId) > 0;
    }

    /**
     * 统计错题数量
     */
    public int countErrorWords(Integer userId) {
        return errorBookMapper.countByUserId(userId);
    }
}

